package com.roc.template.shiro;

import com.roc.template.mongo.model.User;
import com.roc.template.mongo.service.UserService;
import com.roc.template.shiro.jwt.JwtToken;
import com.roc.template.shiro.jwt.JwtUtil;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import javax.annotation.Resource;

/**
 * @ClassName ShiroRealm
 * @Description: TODO
 * @Author Administrator
 * @Date 2020/7/15 10 41
 * @Version V1.0
 **/
public class ShiroRealm extends AuthorizingRealm {

    @Resource
    private UserService userService;


    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof JwtToken;
    }

    @Override
    protected AuthorizationInfo getAuthorizationInfo(PrincipalCollection principals) {
        return super.getAuthorizationInfo(principals);
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        // 获取用户名
        String username = (String) principalCollection.getPrimaryPrincipal();
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        return authorizationInfo;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        // 根据 Token 获取用户名，如果您不知道该 Token 怎么来的，先可以不管，下文会解释
        String token = (String) authenticationToken.getCredentials();
        String  username = JwtUtil.getUsername(token);

        if(username==null) return null;
        // 根据用户名从数据库中查询该用户
        User user = userService.getByUserName(username);
        if(user != null) {
            // 把当前用户存到 Session 中
            // 传入用户名和密码进行身份认证，并返回认证信息
            AuthenticationInfo authcInfo = new SimpleAuthenticationInfo(token, token, "shiroRealm");
            return authcInfo;
        } else {
            return null;
        }
    }

}
